<template>
  <div class="production-plan">
    <el-form-item #default="scope">
      <el-button type="primary" @click="addjihau">保存主表单</el-button>
   
    </el-form-item>
  <!-- 标题 -->
    <div class="page-title">
      <h2>生产补料</h2>
    </div>

    <!-- 基本信息 -->
    <div class="info-section">
      <div class="section-header">基本信息</div>
      <el-form ref="formRef" :model="formData" :rules="rules" label-position="right" label-width="80px">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="单据主题">
              <el-input v-model="formData.documentSubject" placeholder="请输入主题"  />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="单据编号">
              <el-input v-model="formData.documentNumber" placeholder="请输入编号"  disabled/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="来源单据类型" prop="sourceDocumentType" required>
              <el-input v-model="formData.sourceDocumentType" placeholder="系统自动生成" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="来源单据" prop="sourceDocument" required>
              <el-input v-model="formData.sourceDocument" placeholder="系统自动生成" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="制单人员" prop="makingPersonnel">
              <el-input v-model="formData.makingPersonnel" type="textarea"  />
            </el-form-item>
          </el-col>
           <el-col :span="10">
            <el-form-item label="*补料日期" prop="supplementDate">
              <el-date-picker
                v-model="formData.supplementDate"
                type="date"
                required
              ></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="6">
              <el-form-item label="补料数量合计">
                <el-input-number v-model="formData.supplementQuantityTotal" placeholder="请输入数量" :min="0" :step="1" />
              </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="*制单日期" prop="makingDate">
              <el-date-picker
                v-model="formData.makingDate"
                type="date"
                required
              ></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="关联项目" prop="relatedProj">
              <el-input v-model="formData.relatedProj" type="textarea"  />
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="备注" prop="remarks">
              <el-input v-model="formData.remarks" type="textarea"/>
            </el-form-item>
          </el-col>
        </el-row>
         
      </el-form>
    </div>
       <!-- 顶部按钮栏 -->
        <!-- 标题 -->


    <!-- 标题 -->
    <div class="page-title">
      <h2>补料明细</h2>
    </div>
    <!-- 物料明细 -->
    <div class="detail-section">
      <el-button size="small" @click="addNewRow">新增行</el-button>
      <el-button size="small"  @click="batchSaveDetails"> 批量保存明细</el-button>

      <el-table :data="planDetailsList" border style="width: 100%">
        <el-table-column label="产品名称">
           <template #default="{ row }">
            <el-input 
              v-model="row.productName" 
              :readonly="row.isSaved"
            >
              <template #suffix>
                <el-button size="mini" @click="openProductNameDialog(row)">
                  <i class="el-icon-search"></i>
                </el-button>
              </template>
            </el-input>
          </template>
        </el-table-column>
        <el-table-column label="产品编号">
          <template #default="{ row }">
            <el-input v-model="row.productNumber" :readonly="row.isSaved"></el-input>
          </template>
        </el-table-column>
        <el-table-column label="规格型号">
          <template #default="{ row }">
            <el-input v-model="row.specificationModel" :readonly="row.isSaved"></el-input>
          </template>
        </el-table-column>
        <el-table-column label="单位">
          <template #default="{ row }">
            <el-input v-model="row.unit" :readonly="row.isSaved"></el-input>
          </template>
        </el-table-column>
         <el-table-column label="补料数量">
          <template #default="{ row }">
            <el-input-number 
              v-model.number="row.supplementQuantity" 
              :min="0" 
              controls-position="right"
              :disabled="row.isSaved"
            ></el-input-number>
          </template>
        </el-table-column>

        <el-table-column label="出库库管">
          <template #default="{ row }">
            <el-input-number 
              v-model.number="row.currentStock" 
              :min="0" 
              controls-position="right"
              :disabled="row.isSaved"
            ></el-input-number>
          </template>
        </el-table-column>
         <el-table-column label="现有库存">
          <template #default="{ row }">
            <el-input-number 
              v-model.number="row.supplementQuantity" 
              :min="0" 
              controls-position="right"
              :disabled="row.isSaved"
            ></el-input-number>
          </template>
        </el-table-column>
        <el-table-column label="交货日期">
            <template #default="{ row }">
               <el-date-picker
                   v-model="row.deliveryDate"
                    type="date">
                </el-date-picker>
            </template>
        </el-table-column>
           <el-table-column label="补料方式">
          <template #default="{ row }">
            <el-input v-model="row.supplementMethod" :readonly="row.isSaved"></el-input>
          </template>
        </el-table-column>
        <el-table-column label="备注">
          <template #default="{ row }">
            <el-input v-model="row.pickupMethod" :readonly="row.isSaved"></el-input>
          </template>
        </el-table-column>
      

        <el-table-column label="规格">
          <template #default="{ row }">
            <el-input v-model="row.relatedDocument" :readonly="row.isSaved"></el-input>
          </template>
        </el-table-column>
        <el-table-column label="关联项目">
          <template #default="{ row }">
            <el-input v-model="row.relatedProjectt" :readonly="row.isSaved"></el-input>
          </template>
        </el-table-column>

        <el-table-column label="操作">
          <template #default="{ row }">
            <el-button size="small" @click="saveSingleDetail(row)" :disabled="row.isSaved">保存本条</el-button>
              <el-button size="small" type="success" @click="UpdateDetail(row)">修改</el-button> 
            <el-button size="small" type="danger" @click="deleteDetail(row)" :disabled="row.isSaved">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

        <!-- 附件部分 -->
    <div class="attachment-section">
      <h4 class="sub-title">附件管理</h4>
      <el-form ref="formRef" :model="formData" label-width="100px">
        <el-form-item label="选择文件">
          <el-upload ref="uploadRef" action="https://localhost:7269/api/FileUpload/UploadFile" :headers="headers"
            :on-success="handleSuccess" :on-error="handleError" :show-file-list="false" :http-request="customRequest">
            <el-button type="primary">选择文件</el-button>
          </el-upload>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm">上传文件</el-button>
        </el-form-item>
      </el-form>
      <el-table :data="attachments" border style="width: 100%">
        <el-table-column label="文件名称" prop="fileName"></el-table-column>
        <el-table-column label="文件大小" prop="fileSize"></el-table-column>
        <el-table-column label="上传人" prop="uploader"></el-table-column>
        <el-table-column label="上传时间" prop="uploadTime"></el-table-column>
      </el-table>
    </div>

  <!-- 产品名称选择对话框 -->
    <el-dialog
      v-model="productNameDialogVisible"
      width="500px"
      title="产品名称选择"
      append-to-body
    >
      <el-table
        :data="productNames"
        highlight-current-row
        border
        size="small"
        @current-change="handleProductNameChange"
      >
        <el-table-column type="index" label="序号" />
        <el-table-column property="productsNumber" label="产品编号" />
        <el-table-column property="productsName" label="产品名称" />
        <el-table-column property="productsNum" label="规格型号" />
        <el-table-column property="productsUnit" label="单位" />
      </el-table>
      <template #footer>
        <el-button @click="pickProductName">确定</el-button>
      </template>
    </el-dialog>


  </div>
</template>

<script setup>
import { ref, reactive, onMounted, watch } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { useRouter, useRoute } from 'vue-router';
import {Materialwrite,Materialread} from '@/axios/axiosHelper'
import axios from 'axios';
const formRef = ref(null);
const currentUser = ref("admin"); 
const router = useRouter();
const route = useRoute();

// 主表单数据
const formData = reactive({
  'feedingId':0,
  "documentSubject": "",
  "documentNumber": "",
  "sourceDocumentType": "",
  "sourceDocument": "",
  "makingPersonnel":  currentUser.value,
  "supplementDate": "",
  "supplementQuantityTotal": 0,
  "makingDate": "",
  "relatedProj": "",
  "remarks": ""
});

// 主表单验证规则

const rules = reactive({
  documentSubject: [
    { required: true, message: '单据主题不能为空', trigger: 'blur' }
  ],
  pickingDate: [
    { required: true, message: '领料日期不能为空', trigger: 'blur' }
  ],
});

// 明细数据列表
const planDetailsList = ref([]);

const attachments = ref([]);

// 监听路由参数变化
watch(() => route.query, async (newQuery) => {
    if (newQuery.feedingId) {
        await getProductionById(newQuery.feedingId);
    } else {
        // 清空表单
        formData.documentSubject = "";
        formData.documentNumber = "";
        formData.makingPersonnel = currentUser.value;
        formData.sourceDocumentType = "";
        formData.sourceDocument = "";
        formData.supplementDate = "";
        formData.supplementQuantityTotal = 0;
        formData.makingDate = "";
        formData.relatedProj = "";
        formData.remarks = "";
        formData.feedingId = null;
        planDetailsList.value = [];
    }mainData
});

const getProductionById = async (feedingId) => {
    try {
        const [mainResponse, detailResponse] = await Promise.all([
            Materialread.get('/l-read/api/GetValues/FTFeeding', {
                params: { FeedingId: feedingId }
            }),
            Materialread.get('/l-read/api/GetValues/FTFeedDetailss', {
                params: { FeedDetailsId: feedingId }
            })
        ]);

        if (mainResponse.data.code === 200) {
            const mainData = mainResponse.data.data[0];
            formData.documentSubject = mainData.documentSubject;
            formData.documentNumber = mainData.documentNumber;
            formData.makingPersonnel = mainData.makingPersonnel;
            formData.sourceDocumentType = mainData.sourceDocumentType;
            formData.sourceDocument = mainData.sourceDocument;
            formData.supplementDate = mainData.supplementDate;
            formData.supplementQuantityTotal = mainData.supplementQuantityTotal;
            formData.makingDate = mainData.makingDate;
            formData.relatedProj = mainData.relatedProj;
            formData.remarks = mainData.remarks;
            formData.feedingId = mainData.feedingId;

        }
        if (detailResponse.data.code === 200) {
            planDetailsList.value = detailResponse.data.data.map(item => ({
                feedDetailsId: item.feedDetailsId || 0,
                productName: item.productName || "",
                productNumber: item.productNumber || "",
                specificationModel: item.specificationModel || "",
                unit: item.unit || "",
                supplementQuantity: item.supplementQuantity || 0,
                outboundWarehouseManager: item.outboundWarehouseManager ||"",
                currentStock: item.currentStock || 0,
                deliveryDate: item.deliveryDate || "",
                supplementMethod: item.supplementMethod || "",
                specification: item.specification || "",
                relatedDocument: item.relatedDocument || "",
                relatedProjectt: item.relatedProjectt || "",
                feedingId: item.feedingId || '',
              }));
        }
    } catch (error) {
        console.error('查询失败:', error);
        ElMessage.error('数据加载失败，请检查网络或联系管理员');
    }
};
// 保存主表单和明细
const addjihau = async () => {
  if (formRef.value) {
    const isValid = await formRef.value.validate();
    if (isValid) {
      try {
        // 保存主表单
        const response = await axios.put('https://localhost:7077/api/Ment/UpdateFeeding', formData);
        if (response.data.code === 400) {
          formData.feedingId = response.data.data.feedingId;
          ElMessage.success('保存成功');
          router.push('/ShowFeeding');
          // 保存明细
          const saveDetailPromises = planDetailsList.value.map(async (row) => {
            const detailWithId = {
              ...row,
              feedingId: formData.feedingId
            };
            const detailResponse = await Materialwrite.post(
              '/https://localhost:7077/api/Ment/UpdateFeedDetails',
              detailWithId
            );
            if (detailResponse.data.code === 400) {
              row.isSaved = true;
              return true;
            } else {
              ElMessage.error(`明细保存失败：${detailResponse.data.message}`);
              return false;
            }
          });

          const results = await Promise.all(saveDetailPromises);
          if (results.every(result => result)) {
            ElMessage.success('所有明细保存成功');
              router.push('/ShowFeeding');
          }
        } else {
          ElMessage.error(`主表单保存失败：${response.data.message}`);
        }
      } catch (error) {
        // console.error('保存过程中发生错误:', error.response?.data);
        // ElMessage.error('保存过程中发生错误，请检查网络或联系管理员');
      }
    }
  }
};
// // 保存主表单
// const addjihau = async () => {
//     try {
//         const response = await Materialwrite.put('/l-wirth', formData);
//         if (response.data.code === 400) {
//             formData.feedingId = response.data.data.feedingId;
//             ElMessage.success('主表单保存成功');
//         } else {
//             ElMessage.error(`主表单保存失败：${response.data.message}`);
//         }
//     } catch (error) {
//         console.error('保存错误:', error);
//         ElMessage.error('保存失败，请检查网络或联系管理员');
//     }
// };

// 新增行
const addNewRow = () => {
  planDetailsList.value.push({
 "feedDetailsId": '',
  "feedingId": 0,
  "productName": "",
  "productNumber": "",
  "specificationModel": "",
  "unit": "",
  "supplementQuantity": 0,
  "outboundWarehouseManager": "",
  "currentStock": 0,
  "deliveryDate": "",
  "supplementMethod": "",
  "specification": "",
  "relatedDocument": "",
  "relatedProjectt": "",
  
  "isDel": true
  });
};


// 批量保存明细
const batchSaveDetails = async () => {
    // if (!formData.feedingId) {
    //     ElMessage.warning('请先保存主表单');
    //     return;
    // }

    const detailsWithId = planDetailsList.value.map(detail => ({
        ...detail,
        feedingId: formData.feedingId,
    }));

    try {
        const response = await Materialwrite.put(
            ' /l-wirth/api/Ment/UpdateFeedDetails',
            detailsWithId
        );
        if (response.data.code === 400) {
            // 更新 planDetailsList 中的 productionScheduleDetailId
            planDetailsList.value = response.data.data.map((item, index) => ({
                ...planDetailsList.value[index],

                  feedingId: item.feedDetailsId
            }));
            ElMessage.success('明细批量保存成功');
        } else {
            ElMessage.error(`明细批量保存失败：${response.data.message}`);
        }
    } catch (error) {
        console.error('保存错误:', error);
        ElMessage.error('保存失败，请检查网络或联系管理员');
    }
};

// 修改单条明细
const UpdateDetail = async (row) => {
    if (!formData.feedingId) {
        ElMessage.warning('请先保存主表单');
        return;
    }

    const detailData = {
        ...row,
        feedDetailsId: formData.feedingId
    };

    console.log('发送给后端的明细数据:', detailData); // 打印发送给后端的数据

    try {
        const response = await axios.put(
            'https://localhost:7077/api/Ment/UpdateFeedDetails',
            detailData
        );
        console.log('后端返回的响应:', response); // 打印后端返回的响应

        if (response.data.code === 400) {
            ElMessage.success('明细更新成功');
        } else {
            ElMessage.error(`更新失败：${response.data.message}`);
        }
    } catch (error) {
        console.error('更新错误:', error);
        ElMessage.error('更新失败，请检查网络或联系管理员');
    }
};

// 删除单条明细
const deleteDetail = (row) => {
    ElMessageBox.confirm('确认删除该条明细？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(() => {
        const index = planDetailsList.value.indexOf(row);
        if (index !== -1) {
            planDetailsList.value.splice(index, 1);
            ElMessage.success('明细删除成功');
        }
    }).catch(() => {
        ElMessage.info('取消删除');
    });
};

const batchUpload = () => {
    ElMessageBox.confirm('确认上传选中文件？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(() => {
        ElMessage.info('批量上传功能待完善具体逻辑');
    });
};

onMounted(() => {
    if (route.query.feedingId) {
        getProductionById(route.query.feedingId);
    }
    fetchProducts();
});



// 产品名称数据
const productNames = ref([]);

const productNameDialogVisible = ref(false);
const currentProductNameRow = ref(null);
const currentProductName = ref({});

// 获取产品信息
const fetchProducts = () => {
  axios.get("https://localhost:7095/api/Products/GetProducts")
    .then(res => {
      productNames.value = res.data.data;
      console.log("产品数据：", productNames.value);
      nextTick(() => {
        // 强制更新表格
      });
    })
    .catch(error => {
      // console.error('获取产品信息失败:', error);
      // ElMessage.error('获取产品信息失败，请检查网络或联系管理员');
    });
};



// 打开产品名称选择对话框
const openProductNameDialog = (row) => {
  if (productNames.value.length === 0) {
    ElMessage.warning('产品信息正在加载，请稍后重试');
    return;
  }
  currentProductNameRow.value = row;
  productNameDialogVisible.value = true;
};

// 当前选中的产品名称行
const handleProductNameChange = (val) => {
  currentProductName.value = val;
};

// 选择产品名称
const pickProductName = () => {
  if (currentProductName.value && currentProductNameRow.value) {
    currentProductNameRow.value.productName = currentProductName.value.productsName;
    currentProductNameRow.value.productNumber = currentProductName.value.productsNumber;
    currentProductNameRow.value.specificationModel = currentProductName.value.productsNum;
    currentProductNameRow.value.unit = currentProductName.value.productsUnit;
    currentProductNameRow.value.productInfoFilled = true; // 设置标志位，表示产品信息已填充
    productNameDialogVisible.value = false;
  }
};


</script>

<style scoped>
.production-plan {
    padding: 20px;
}

.title {
    text-align: center;
    margin-bottom: 20px;
}

.sub-title {
    margin: 20px 0 10px;
    font-size: 16px;
    font-weight: 500;
}

.detail-section,
.attachment-section {
    margin-top: 20px;
}

.el-table {
    margin-top: 10px;
}
</style>    